using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Razor.TagHelpers;
using WalkingTec.Mvvm.Core;
using System.Linq;
using WalkingTec.Mvvm.Core.Extensions;
using System.Text.Json;

namespace ReaWTM.LayuiHelper
{
	/// <summary>
	/// layui多文件上传
	/// </summary>
	[HtmlTargetElement("wt:multiupload", Attributes = REQUIRED_ATTR_NAME, TagStructure = TagStructure.WithoutEndTag)]
	public class MultiUploadTagHelper : BaseFieldTag
	{
		public string ButtonText { get; set; }

		/// <summary>
		/// 限定上传文件大小，单位K
		/// </summary>
		public int FileSize { get; set; }

		/// <summary>
		/// 上传文件类别
		/// </summary>
		public UploadTypeEnum UploadType { get; set; }

		/// <summary>
		/// 当上传文件类别为ImageFile时，指定缩小的宽度，框架会使用缩小后的图片保存
		/// </summary>
		public int? ThumbWidth { get; set; }

		/// <summary>
		/// 当上传文件类别为ImageFile时，指定缩小的高度，框架会使用缩小后的图片保存
		/// </summary>
		public int? ThumbHeight { get; set; }

		/// <summary>
		/// 是否使用缩略图预览，当上传文件类别为ImageFile时，默认为true
		/// </summary>
		public bool? ShowPreview { get; set; }

		/// <summary>
		/// 如果使用缩略图预览，指定缩略图宽度，默认64
		/// </summary>
		public int? PreviewWidth { get; set; }

		/// <summary>
		/// 如果使用缩略图预览，指定缩略图高度，默认64
		/// </summary>
		public int? PreviewHeight { get; set; }

		public string CustomType { get; set; }
		/// <summary>
		/// 同时上传的文件数（0不限制）
		/// </summary>
		public int NumFileOnce { get; set; }
		public string ConnectionString { get; set; }
		public string ExtraQuery { get; set; }
		public string UploadGroupName { get; set; }
		public string UploadSubdir { get; set; }
		public string UploadMode
		{
			get; set;
		}
		public override void Process(TagHelperContext context, TagHelperOutput output)
		{
			output.TagMode = TagMode.StartTagAndEndTag;
			var vm = context.Items["model"] as BaseVM;
			var url = "/_Framework/Upload?1=1";
			if (UploadType == UploadTypeEnum.ImageFile)
			{
				if (ShowPreview == null || ShowPreview == true)
				{
					ShowPreview = true;
					if (PreviewWidth == null && PreviewHeight == null)
					{
						PreviewHeight = 64;
						PreviewWidth = 64;
					}
					var text = "点击上传，或将文件拖拽到此处";
					if (!string.IsNullOrEmpty(ButtonText))
					{
						text = ButtonText;
					}

					output.TagName = "div";
					output.Attributes.Add("class", "layui-upload-drag wtm-upload-drag");
					output.Content.AppendHtml($"<i class='layui-icon layui-icon-upload'><p class='layui-font-12'>{text}</p></i>");
					output.PostElement.AppendHtml($@"<div id='{Id}div'></div>");
				}
				url = "/_Framework/UploadImage?1=1";
				if (ThumbWidth != null)
				{
					url += "&width=" + ThumbWidth;
				}
				if (ThumbHeight != null)
				{
					url += "&height=" + ThumbHeight;
				}
			}
			else
			{
				output.TagName = "button";
				output.Attributes.Add("class", "layui-btn layui-btn-normal wtm-upload-btn");
				output.Attributes.Add("type", "button");

				output.PostElement.AppendHtml($@"<div id='{Id}div'></div>");
				if (string.IsNullOrEmpty(ButtonText))
				{
					output.Content.SetHtmlContent(THProgram._localizer["Sys.Select"]);
				}
				else
				{
					output.Content.SetHtmlContent(ButtonText);
				}
			}
			output.Attributes.Add("id", Id + "button");
			output.Attributes.Add("name", Id + "button");
			if (string.IsNullOrEmpty(ConnectionString) == true)
			{
				if (vm != null)
				{
					url = url.AppendQuery($"_DONOT_USE_CS={vm.CurrentCS}");
				}
			}
			else
			{
				url = url.AppendQuery($"_DONOT_USE_CS={ConnectionString}");
			}
			if (string.IsNullOrEmpty(UploadGroupName) == false)
			{
				url = url.AppendQuery($"groupName={UploadGroupName}");
			}
			if (string.IsNullOrEmpty(UploadSubdir) == false)
			{
				url = url.AppendQuery($"subdir={UploadSubdir}");
			}
			if (string.IsNullOrEmpty(UploadMode) == false)
			{
				url = url.AppendQuery($"sm={UploadMode}");
			}
			url = url.AppendQuery(ExtraQuery);

			string idstring = "";
			if (Field.Model is IEnumerable<ISubFile> subfiles)
			{
				idstring = subfiles.Select(x => x.FileId.ToString()).ToSepratedString(seperator: "|");
			}

			if (Disabled == true)
			{
				output.Attributes.Add("style", "display:none");
			}
			string ext = "";
			if (string.IsNullOrEmpty(CustomType))
			{
				switch (UploadType)
				{
					case UploadTypeEnum.AllFiles:
						ext = "";
						break;
					case UploadTypeEnum.ImageFile:
						ext = "jpg|jpeg|gif|bmp|png|tif";
						break;
					case UploadTypeEnum.ZipFile:
						ext = "zip";
						break;
					case UploadTypeEnum.ExcelFile:
						ext = "xls|xlsx";
						break;
					case UploadTypeEnum.PDFFile:
						ext = "pdf";
						break;
					case UploadTypeEnum.WordFile:
						ext = "doc|docx";
						break;
					case UploadTypeEnum.TextFile:
						ext = "txt";
						break;
				}
			}
			else
			{
				ext = CustomType;
			}


			string initselected = "[";
			foreach (var fileId in idstring.Split('|', StringSplitOptions.RemoveEmptyEntries))
			{
				initselected += $"'{fileId}',";
			}
			if (initselected.EndsWith(","))
			{
				initselected = initselected.Substring(0, initselected.Length - 1);
			}
			initselected += "]";

			output.PostElement.AppendHtml($@"
<script>
wtm.multiupload_Render({{
{(PreviewHeight == null ? "" : $"previewHeight:{PreviewHeight},")}
{(PreviewWidth == null ? "" : $"previewWidth:{PreviewWidth},")}
{(ShowPreview == null ? "" : $"showPreview:{ShowPreview.ToString().ToLower()},")}
cs:'{(vm != null ? vm.CurrentCS : "")}',
disabled:{Disabled.ToString().ToLower()},
ext:'{ext}',
fileSize:{FileSize},
id:'{Id}',
numFileOnce:{NumFileOnce},
sysDelete:'{THProgram._localizer["Sys.Delete"]}',
sysUploadFailed:'{THProgram._localizer["Sys.UploadFailed"]}',
url:'{url}',
selectedData:{initselected},
fieldName:'{Field.Name}'
}});
</script>
".Replace("\r\n", ""));

			if (string.IsNullOrEmpty(idstring) == false)
			{
				var allfileids = idstring.Split('|', StringSplitOptions.RemoveEmptyEntries);
				output.PostElement.AppendHtml($@"
<script>
wtm.multiupload_AjaxGet({{
{(PreviewHeight == null ? "" : $"previewHeight:{PreviewHeight},")}
{(PreviewWidth == null ? "" : $"previewWidth:{PreviewWidth},")}
{(ShowPreview == null ? "" : $"showPreview:{ShowPreview.ToString().ToLower()},")}
allfileids:{JsonSerializer.Serialize(allfileids)},
cs:'{(vm != null ? vm.CurrentCS : "")}',
disabled:{Disabled.ToString().ToLower()},
ext:'{ext}',
fieldName:'{Field.Name}',
fileSize:{FileSize},
geturl:'/_Framework/GetFileName',
id:'{Id}',
numFileOnce:{NumFileOnce},
selectedData:{initselected},
sysDelete:'{THProgram._localizer["Sys.Delete"]}',
sysUploadFailed:'{THProgram._localizer["Sys.UploadFailed"]}'
}});
</script>
".Replace("\r\n", ""));

			}
			base.Process(context, output);

		}

		protected override void SetRequired(TagHelperOutput output)
		{
			string layverify = "required";
			if (!string.IsNullOrEmpty(LayVerify))
			{
				layverify = $"{layverify}|{LayVerify}";
			}

			output.PostElement.AppendHtml($@"
<input type='hidden' id='{Id}' lay-verify='{layverify}' lay-reqText='{THProgram._localizer["Validate.{0}required", Field?.Metadata?.DisplayName ?? Field?.Metadata?.Name]}' >");
		}
	}
}
